package per.zhen.common.string;

import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringReplacement {
    private String startTag = "\\$\\{";
    private String endTag = "\\}";
    private String expresion;
    
    public StringReplacement() {
    	expresion = startTag + buildGroup() + "*" + endTag;
    }
    
    public StringReplacement(String startTag,String endTag) {
    	this.startTag = startTag;
    	this.endTag = endTag;
    	expresion = startTag + buildGroup() + "*" + endTag;
    }
    
    public StringReplacement(String expresion) {
    	this.expresion = expresion;
    }
    
    public String replace(String orgString,Function<String,String> dealFun) {
    	Pattern p = Pattern.compile(expresion);
    	Matcher m = p.matcher(orgString);
    	StringBuffer sb = new StringBuffer();
    	while (m.find()) {
    		String matchedString = m.group();
    		String dealString = dealFun.apply(matchedString);
    		m.appendReplacement(sb, dealString);
    	}
    	return sb.toString();
    }
    
    private String buildGroup() {
    	return "[^" + startTag + endTag + "]";
    }
    
    public static void main(String[] args) {
    	StringReplacement replacement = new StringReplacement();
    	String result = replacement.replace("fewfew${ceshiw}sfw12${12345}", str->{
    		System.out.println(str);
    		return "A";
    	} );
    	System.out.println(result);
	}
    
}
